package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ghy
 * @version 1.0.1
 * @date 2023-04-25 11:49:09
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public Result<UserLoginVO> login(UserLoginDTO userLoginDTO) {
        //1.调用微信接口获取openid
        String openid = getOpenid(userLoginDTO);
        //2.根据openid查询用户是否存在
        User user = userMapper.getByOpenid(openid);
        if(user == null) {
            //没有对应的用户
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        //生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        //封装数据
        UserLoginVO loginVO = UserLoginVO.builder()
                .id(user.getId()).
                openid(openid)
                .token(token)
                .build();
        return Result.success(loginVO);
    }

    private String getOpenid(UserLoginDTO userLoginDTO) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(url, paramMap);
        Map<String, Object> map = JSON.parseObject(json, Map.class);
        String openid = (String) map.get("openid");
        log.warn("openid:{}", openid);
        return openid;
    }
}
